package com.tcm.config;

import com.tcm.common.Interceptor.AuthInterceptor;
import com.tcm.common.Interceptor.CorsInterceptor;
import com.tcm.common.JacksonObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * MVC全局配置类
 */
@Slf4j
@Configuration
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {

    @Bean
    public AuthInterceptor authInterceptor() {// 将权限验证拦截器纳入Spring Ioc容器管理
        return new AuthInterceptor();
    }

    /**
     * MVC拦截器
     * @param registry 拦截器注册对象
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new CorsInterceptor());
        log.info("注册CORS跨域拦截器");
        registry.addInterceptor(authInterceptor())
                .excludePathPatterns("/pc/auth/login")// PC用户登录
                .excludePathPatterns("/pc/auth/code")// PC获取验证码
                .excludePathPatterns("/stu/auth/wxLogin")// 学生微信登录
                .excludePathPatterns("/stu/auth/login")// 通用学生登录
                .excludePathPatterns("/stu/auth/pc/login")
                .excludePathPatterns("/stu/auth/pc/code");
        log.info("注册Auth权限验证拦截器");
    }

    /**
     * 扩展MVC的消息转换器
     * @param converters
     */
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        // 创建消息转换器对象
        MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
        //  设置对象转换器，底层使用Jackson将Java对象转换为json
        messageConverter.setObjectMapper(new JacksonObjectMapper());
        // 将上面的消息转换器对象追加到MVC框架的转换器集合中
        converters.add(0, messageConverter);
    }

}
